
import {reqAlldingdan,reqOrderdetail,cancelOrder} from '../../../api/mine'
import {reqUpdorder} from '../../../api/order'
import {confirmDeduction,releaseLockedInventory} from '../../../api/inventory'

Page({
  /**
   * 页面的初始数据
   */
  data: {
    time: 30 * 60 * 60 * 1000,
    activeasd: 1,
    // 订单数据
    orders: [{}],
    password:'',
    passwordLength:6,
    usepasstrue:false,
    showpay: false,
    ooo:[],
    submittedInvoiceIds: '', // 已开发票的订单ID数组
    invoiceStatus: {} ,
    token:'',
    user:{},
  },
  // 点击订单项事件
  handleOrderTap(e) {
    const clickedOrder = e.currentTarget.dataset.order;
    console.log("点击的订单对象：", clickedOrder);
    this.setData({
      ooo:clickedOrder
    })
    setTimeout(()=>{
      wx.navigateTo({
        url: '/pages/orderdetails/orderdetails?orderInfo='+JSON.stringify(clickedOrder),
      })
    },1000)
   
  },
  gotoPayment(){
    this.setData({
      showpay:true
    })
  },
  
  usepass(){
    this.setData({
      usepasstrue:true,
      showpay:false
    })
  },
  onClickHide() {
    this.setData({ showpay: false });
  },
  // 处理输入事件，更新密码
  handleInput(e) {
    this.setData({
      password: e.detail.value
    });
    if (e.detail.value.length === this.data.passwordLength) {
      const input = this.selectComponent('#passwordInput');
      input && input.blur();
      this.setData({ usepasstrue: false });
    
     reqUpdorder(1,this.data.ooo.orderNo)
    .then(response => {
      if (response === "修改成功") {
        console.log("修改成功")
        console.log(this.data.ooo)
    
             let yeartoday=this.data.tourdate.substring(0,10);
             console.log(yeartoday)
             confirmDeduction(this.data.ooo.detailInfo[0].productId,this.data.ooo.detailInfo[0].productType,yeartoday,this.data.ooo.quantity)
      } else {
        console.error("订单状态更新失败");
      }
    })// 修改后代码
    .then(() => {
      this.setData({ password: '' });
      this.all(2); 
      // this.setData({
      //   activeasd: 0 
      // });
  
    })
    .catch(error => {
      console.error("请求失败", error);
    });
      console.log('输入的密码：', e.detail.value);
    }
  },
  gotofapiao(e){
    const clickedOrder = e.currentTarget.dataset.order;
    this.setData({
      ooo:clickedOrder
    })
// 如果已开发票，显示提示
if (this.hasInvoice(clickedOrder.id)) {
  wx.showToast({
    title: '该订单已开发票',
    icon: 'none',
    duration: 2000
  });
  const fa=wx.getStorageSync('fapiao');
  wx.navigateTo({
    url: `/pages/invoice/fapiao/fapiao?f=${encodeURIComponent(fa)}`,
  })
  return;
}
    wx.navigateTo({
      url: `/pages/invoice/invoice?zhi=${encodeURIComponent(JSON.stringify(this.data.ooo))}`
    })
  },
  cancelOrder(e){
    let that=this;
    wx.showModal({
      title: '取消订单',         // 标题（可选）
      content: '确定执行此操作吗？', // 内容
      cancelText: '取消',        // 否按钮文字（默认"取消"）
      confirmText: '确定',       // 是按钮文字（默认"确定"）
      cancelColor: '#000000',    // 否按钮颜色（可选）
      confirmColor: '#576B95',   // 是按钮颜色（可选）
      success(res) {
        if (res.confirm) {
          cancelOrder(e.currentTarget.dataset.orderid.id,2).then(data=>{
            console.log(data)
          })
          let gun=e.currentTarget.dataset.orderid
          console.log(gun.tourdate.substring(0,10))
          releaseLockedInventory(gun.detailInfo[0].productId,gun.detailInfo[0].productType,gun.tourdate.substring(0,10),gun.quantity)
          wx.showToast({
            title: '取消成功',
          })
          that.all(0);
        } else if (res.cancel) {
          // 执行取消操作
          wx.showToast({
            title: '操作取消',
          })
        }
      }
    })
  },

 async all(num){
  this.setData({ activeasd: num });
    let status='';
   if(num==1){
      //待支付 对应数据库
      status=0
    }else if(num==2){
      //待消费 对应数据库
      status=1 
    }else if(num==3){
      //待评价 对应数据库
      status=3
    }else if(num==4){
      //待退款
      status=4
    }

    const orderListRes = await reqAlldingdan(status, wx.getStorageSync('userInfo').userId);
    const orderList = orderListRes.data.alldingdan || [];
    
    // 2. 并行获取所有订单详情
    const detailRequests = orderList.map(order => {
      // 必须返回 Promise 对象
      return reqOrderdetail(order.detailId, wx.getStorageSync('userInfo').userId).then(res => {
        return res;
      });
    });
    const detailResponses = await Promise.all(detailRequests);
    
    // 3. 合并数据
    const mergedOrders = orderList.map((order, index) => {
      const merged = {
        ...order,
        detailInfo: detailResponses[index].data.orderdetail || {}
      };
      return merged;
    });

    //紧急插播一条倒计时
    console.log(mergedOrders)
    if(num==1){
      mergedOrders.forEach((item)=>{
        let time=new Date(item.createTime)//订单创建时间
        let now=new Date()
        let nowTime=now.getTime() //现在时间
        let endtime=time.getTime()+15 * 60 * 1000 //订单十五分钟过期截止时间
        item.lasttime=endtime-nowTime-57600000
      })
    }

    // 4. 设置数据
    this.setData({
      orders: mergedOrders
    }, () => {
      mergedOrders.forEach(order => {
        this.hasInvoice(order.id); 
      });
    }); 
    // 5. 最终检查
    console.log('4. 最终设置的数据:', this.data.orders);  // 最终数据
  },
  onlastTime(e){
    let that=this
    reqUpdorder(2,e.currentTarget.dataset.orderno).then(data=>{
      console.log("过期订单"+e.currentTarget.dataset.orderno+data)
      let list=that.data.orders
      list=list.filter(item=>{
        return item.orderNo!=e.currentTarget.dataset.orderno
      })
      that.setData({
        orders:list
      })
    })
  },
  onChange(event) {
    if(wx.getStorageSync('userInfo').userId == null) return;
    
    // 获取点击的标签页索引 (0,1,2,3,4)
    const tabIndex = event.detail.name;
    
    // 将标签索引转换为对应的业务状态编号
    let businessState = 0;
    if(tabIndex === 0) businessState = 0;       // 全部订单
    else if(tabIndex === 1) businessState = 1;  // 待付款
    else if(tabIndex === 2) businessState = 2;  // 待消费
    else if(tabIndex === 3) businessState = 3;  // 待评价
    else if(tabIndex === 4) businessState = 4;  // 售后
    
    // 调用 all 方法加载数据
    this.all(businessState);
    
    this.setData({
      showpay: false,
      usepasstrue: false
    });
  },
  onusers(){
    const userInfo=wx.getStorageSync('userInfo');
    const token=wx.getStorageSync('token')
    if(token!=null){
      this.setData({
        user:userInfo,
        token
      })
    }
  },

  onLoad(options) {
    this.onusers()
    if(wx.getStorageSync('userInfo').userId==null || wx.getStorageSync('userInfo').userId==''){
      return;
  
    }else{
    const storedIds = wx.getStorageSync('submittedInvoiceIds') || '';
    
    this.setData({ submittedInvoiceIds: storedIds });
    console.log("onload:"+storedIds)
    console.log("onload:"+typeof(storedIds))
   
    let num=options.tabid
   this.all(num)
      this.setData({
        activeasd: parseInt(num),
        //orders: storedOrders
      });
    console.log(this.data.activeasd)
    }
  },
  // 返回上一页
  navigateBack() {
    wx.navigateBack({
      delta: 1
    });
  },
  //去评价
  gotoComment(e){
    console.log(e.currentTarget.dataset)
    wx.navigateTo({
      url: '/pages/mine/evaluate/evaluate?orderid='+e.currentTarget.dataset.orderid+"&productid="+e.currentTarget.dataset.productid+"&producttype="+e.currentTarget.dataset.producttype,
    })
  },

  // 待消费查看二维码跳转页面
  gotoQRcode(e) {
    const clickedOrder = e.currentTarget.dataset.order;
    this.setData({
      ooo:clickedOrder
    })
    const orderid = e.currentTarget.dataset.orderid;
    console.log(this.data.ooo)
    wx.navigateTo({
      url: `/pages/mine/ewm/ewm?ooo=${encodeURIComponent(JSON.stringify(this.data.ooo))}`
    });
  },
// 订单页判断方法
hasInvoice(id) {
  // 目标ID转为字符串
  const targetId = String(id);
  // 读取存储的字符串
  const storedIds = wx.getStorageSync('submittedInvoiceIds') || '';
  let aa=storedIds.split(',').includes(targetId);
  // 存储当前订单的状态到对象中
  this.setData({
    [`invoiceStatus.${targetId}`]: aa
  });
  
  return aa;
},

  // 去首页
  gotoHome() {
    wx.switchTab({
      url: '/pages/index/index'
    });
  },
  
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    
  }
})